package client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * The RequestThread class executes an http request by sending it to the server and receiving the response
 * @author Askar Rizvi, Denis Zgonjanin
 *
 */
class RequestThread implements Runnable{
	
	private Socket threadSocket;
	private PrintWriter out;
	private BufferedReader in;
	private String httpRequest;
	private String ip;
	private int port;
	
	/**
	 * The constructor. Creates a new RequestThread, ready to be ran
	 * @param socket - The socket through which the class communicates with the server
	 * @param httpRequest - The http request to be processed
	 */
	public RequestThread(String ip, int port, String httpRequest){
		this.ip = ip;
		this.port = port;
		this.httpRequest = httpRequest;
	}
	
	/**
	 * The run method of this thread. Should not be called directly. Use start() instead
	 */
	public void run(){
		try{
			this.threadSocket = new Socket(ip, port);
		} catch (Exception e){
			System.out.println(e.getMessage());
		}
		try {
			out = new PrintWriter(threadSocket.getOutputStream(), true);
		    in = new BufferedReader( new InputStreamReader( threadSocket.getInputStream()));
		}catch (IOException e2) {
		   	System.err.println(e2.getMessage());
		   	System.exit(1);
		}
		try{	  

		   	out.println(httpRequest);
		   	
		   	String logStr = "";
		   	String s;
		   	while ((s = in.readLine())!= null){
		   		logStr = logStr.concat(s);
		   	}
		   	//logStr = in.readLine();
		   	
		   	Client.log = Client.log + logStr;
		   	System.out.println(logStr);
		   	out.close();
		   	in.close();
		   	threadSocket.close();
		   	
		}catch (IOException e) { 
		   	System.err.println(e.getMessage());
		   	System.exit(1);
		}
	}
	   
}